package routers

import (
	"github.com/astaxie/beego/context"
	"lazyops_go/models"
	"regexp"
)


//登陆判断
var LoginFilter = func(ctx *context.Context){
	cur_user := ctx.Input.Session("cur_user")
	if cur_user==nil{
		//不需要权限控制的路由地址
		notPermission := []string{"/","/login/","/api/"}
		flag := false
		for _,v := range notPermission{

			if v == ctx.Request.RequestURI {
				flag = true
				break
			}
			r, _ := regexp.Compile(v)
			if r.MatchString(ctx.Request.RequestURI){
				flag = true
				break
			}
		}
		if !flag{
			ctx.Redirect(302, "/")
		}
	}
}

//权限判断
var PermsFilter = func(ctx *context.Context){
	req_method := ctx.Input.Method()

	//记录登陆日志
	obj := models.LogUser{}
	cur_user := ctx.Input.Session("cur_user")
	if cur_user!= nil{
		obj.UserName = cur_user.(string)
	}else{
		ctx.Redirect(302, "/")
	}
	//请求地址
	req_url := ctx.Request.RequestURI

	//查询请求地址权限
	req_menu := models.GetPermsUrl(req_url)

	obj.Req = req_menu.MenuTitle
	obj.ReqMenu = models.GetMenuId(req_menu.PMenu).MenuTitle

	//需配置copyrequestbody = true 否则返回[]
	obj.ReqData = string(ctx.Input.RequestBody)
	req_url_id := int(req_menu.ID)

	is_super := ctx.Input.Session("is_super").(bool)
	var flag bool
	if is_super{
		obj.Status = "success"
		flag = true
	}else{
		//获取当前session中的权限
		cur_perms:= ctx.Input.Session("cur_user_perms")
		if cur_perms != nil {
			notPermission := []string{"/","/login/","/logout/"}

			for _,v := range notPermission{
				if v == ctx.Request.RequestURI{
					flag = true
					break
				}
			}
			if !flag{
				check := isExitItem(req_url_id,cur_perms.([]int))
				if !check{
					obj.Status = "无权访问"
					ctx.ResponseWriter.Write([]byte("无权访问"))
				}else{
					obj.Status = "success"
				}
			}
		}
	}

	if req_method != "GET"{
		models.AddLogUser(obj)
	}
}

func isExitItem(val int,array []int)  bool {
	for _,v := range array{
		if v == val{
			return true
		}
	}
	return false
}
